package com.hoyu.time.server;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Date;


public class TimeServer {
	
	private boolean status;
	
	private ServerSocket ss;
	
	private static final int PORT = 12345;
	
	//private ExecutorService service;
	
	
	public boolean start() throws IOException {
		ss = new ServerSocket(PORT);
		status = true;
		while(status) {
			Socket socket = ss.accept();
			System.out.println("connected...");
			new Thread(new Runnable() {
				
				@Override
				public void run() {
					System.out.println("handle Thread start");
					try {
						
						while (status){
							handle(socket);
						}
					}
					catch(IOException e) {
						e.printStackTrace();
					}
				}
			}).start();
		}
		return status;
	}
	
	
	public boolean stop() {
		return status;
	}
	
	
	private void handle(Socket socket) throws IOException{
		BufferedReader in=new BufferedReader(new InputStreamReader(socket.getInputStream())); 
		PrintWriter out=new PrintWriter(socket.getOutputStream()); 
		String str=in.readLine(); 
		System.out.println("rec:"+str);
		if("date".equals(str)) {
			Date date = new Date();
			out.println(date.toString());
			out.flush();
		}
	}
	
	public static void main(String[] args) {
		TimeServer server = new TimeServer();
		try {
			server.start();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

}
